<%@page language="java" contentType="text/html; charset=UTF-8" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="html" tagdir="/WEB-INF/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<html:header title="编辑商品套餐">

    <link rel="stylesheet" href="${baseUrl}css/public.css" media="all">


    <style type="text/css">
        a{
            color: #01AAED;
            text-decoration: none;
            font-size: 12px;
        }
        a:hover {
            color: #FF5722;
        }

        .layui-table-view{
            margin: 0;
        }
        .layui-table-cell {            overflow: visible !important;        }
        /* 使得下拉框与单元格刚好合适 */
        td .layui-form-select{
            margin-top: -10px;
            margin-left: -15px;
            margin-right: -15px;
        }
    </style>

    <script>
        jQuery(function () {
            fixTableOperatorButton();

            $("#cancel").click(function () {
                closeSubIframe();
            });

            $("#save").click(function () {
                $("[lay-filter='save']").click();
            });

            $(".select-goods").click(function () {
                openBigHtmlDialog("选择商品", "${baseUrl}select/selectGoods.action?sn=false&priceFlag=4");
            });

            $("#totalAmount").blur(function () {
                let amt = genAmount($(this).val());
                $(this).val(getPrice(amt));
            });

            if(isTrue("${used}")) {
                errTip("该商品套餐已经被业务单据引用，不能新增或删除成分商品");
            }
        });

        layui.use(['form', 'table'], function () {
            let $ = layui.jquery,
                form = layui.form,
                table = layui.table,
                util = layui.util;

            get("${baseUrl}marketGoods/goodsPacket/getVoById.action?id=${id}", function (res) {
                if (res.code == 1) {
                    res.data.totalAmount = getPrice(res.data.price);
                    if (res.data.status == 1) {
                        res.data.status = true;
                    } else {
                        res.data.status = false;
                    }
                    formSetVal("form",res.data);

                    let list=[];
                    $.each(res.data.packetGoodsVoList, function (i,d) {
                        let goodsVo = d.goodsVo;
                        goodsVo.number = d.number;
                        goodsVo.unitId = d.unitId;
                        goodsVo.times = d.times;
                        goodsVo.price = d.price;
                        goodsVo.amount = d.amount;
                        list.push(goodsVo);
                    });
                    renderTable(list);
                }
            });

            // 监听修改update到表格中
            form.on('select(unitSelect)', function (data) {
                let index = $(data.elem).parents('tr').data('index');
                let tableData = layui.table.cache.table;
                let goodsUnitVo = genUnitVo(tableData[index].goodsUnitVoList, data.value);
                $(data.elem).parents('tr').find(".price").val(getPrice(goodsUnitVo.retailPrice));


                $(data.elem).parents('tr').find(".retailPrice").html("零售价："+getPrice(goodsUnitVo.retailPrice));
                $(data.elem).parents('tr').find(".retailPrice").attr("price",getPrice(goodsUnitVo.retailPrice));
                $(data.elem).parents('tr').find(".wholesalePrice").html("进货价："+getPrice(goodsUnitVo.wholesalePrice));
                $(data.elem).parents('tr').find(".wholesalePrice").attr("price",getPrice(goodsUnitVo.wholesalePrice));

                tableData[index].unitId = data.value;
                tableData[index].times = goodsUnitVo.times;
                tableData[index].price = goodsUnitVo.retailPrice;
                processAmount($(data.elem));
            });

            form.on('submit(save)',function (data) {
                if (layui.table.cache.table.length == 0) {
                    tip("未选择任何商品");
                    return false;
                }

                if (data.field.name == "") {
                    tip("套餐名称不能为空");
                    return false;
                }

                if (data.field.no == "") {
                    tip("套餐名称不能为空，请点击重新获取");
                    return false;
                }

                let flag = false;
                $.each(layui.table.cache.table,function (i,d) {
                    if (d.number == 0) {
                        errTip(d.name+"的数量不能为空");
                        flag = true;
                        return false;
                    }
                });
                if (flag){
                    return false;
                }

                //套餐
                let packetVo = data.field;
                packetVo.price = data.field.totalAmount;
                delete packetVo.number;
                delete packetVo.unitId;
                delete packetVo.amount;
                delete packetVo.totalAmount;
                if (data.field.status == undefined) {
                    packetVo.status = 2;
                } else {
                    packetVo.status = 1;
                }
                //套餐商品
                let packetGoodsList = new Array();

                $.each(layui.table.cache.table,function (i,d) {
                    let packetGoods = {};
                    packetGoods.goodsId = d.id;
                    packetGoods.unitId = d.unitId;
                    packetGoods.times = d.times;
                    packetGoods.price = d.price;
                    packetGoods.number = d.number;
                    packetGoods.amount = d.amount;
                    packetGoodsList.push(packetGoods);
                });

                packetVo.packetGoodsList = packetGoodsList;

                console.log(JSON.stringify(packetVo));
                tipLoad("套餐新增中...");
                post("${baseUrl}marketGoods/goodsPacket/update.action", packetVo, function (res) {
                    closeAll();
                    if (res.code == 1) {
                        refreshMainIframe("${baseUrl}marketGoods/packet.action");
                        closeSubIframe();
                        tip('更新成功');
                    } else {
                        errTip(res.msg);
                    }
                });
                return false;
            });
        });

        function renderTable(list) {
            layui.table.render({
                id:'table',
                elem: '#table',
                height: 300,
                data:list,
                text: {
                    none: '未选择商品' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
                },
                cols: [[
                    {type:'numbers'},
                    {field: 'no', width: 120, title: '商品编号',style:"font-size:12px;"},
                    {field: 'name', minWidth: 140, title: '名称/规格',style:"font-size:12px;",templet:function (d) {
                            return genGoodsName(d.name,d.norms);
                        }},
                    {width: 80, title: '数量',templet:"#numberBar"},
                    {width: 100, title: '单位',style:"font-size:12px;", templet:function (d) {
                            return genSelectUnit(d.unitId,d.goodsUnitVoList);
                        }},
                    { width: 80, title: '单价',templet:'#priceBar'},
                    { width: 80, title: '金额',style:"font-size:12px;",templet:"#amountBar"},
                    <c:if test="${!used}">
                    {title: '操作', minWidth: 80, fixed:'right', templet: '#operBar'},
                    </c:if>
                ]],
                limit: Number.MAX_VALUE,
                done: function(res, curr, count){
                    setTotalAmount();

                    $(".priceDiv").unbind("mouseenter").bind("mouseenter", function() {
                        $(this).find(".priceListDiv").css("display","block");
                    });
                    $(".priceDiv").unbind("mouseleave").bind("mouseleave", function() {
                        $(this).find(".priceListDiv").css("display","none");
                    });

                    $(".subjectPrice").unbind("click").bind("click", function () {
                        $(this).parents(".priceDiv").find(".priceListDiv").css("display","none");
                        let price = $(this).attr("price");
                        $(this).parents(".priceDiv").find(".price").val(price);

                        let index = $(this).parents('tr').data('index');
                        let tableData = layui.table.cache.table;
                        tableData[index].price = price;
                        processAmount($(this));
                    });

                    $(".price").unbind("blur").bind("blur",function () {
                        $(this).val(getPrice($(this).val()));
                        let index = $(this).parents('tr').data('index');
                        let tableData = layui.table.cache.table;
                        tableData[index].price = getPrice($(this).val());
                        processAmount($(this));
                    });


                    $(".amount").unbind().bind('blur',function () {
                        setAmount(genAmount($(this).val()), $(this));
                    });

                    $(".number").unbind().bind('blur',function () {
                        processNumber(genNumber($(this).val()),$(this));
                    });
                }
            });

            layui.table.on('tool(table)', function (obj) {
                let data = obj.data;
                if (obj.event === 'delete') {
                    operator_del(obj);
                }
            });
        }


        /**
         * 如果使用商品选择窗口，必须实现此函数，否则取不到已选择的商品数据
         * @param data
         */
        function getSelectGoods(data) {
            console.log("选择商品数据");
            console.log(JSON.stringify(data));
            //处理显示数据
            $.each(data,function (i,d) {
                layui.table.cache.table.push(d);
            });

            setTotalAmount();
            reloadGoodsTable();
            $(window).focus();
        }

        /**
         * 供外部调用-根据条码获取商品接口
         * @param data
         */
        function processGoods(data) {
            $(window).focus();
            layui.table.cache.table.push(data);
            reloadGoodsTable();
            setTotalAmount();
        }


    </script>

</html:header>
<body>
<div style="width: 100%; margin-bottom: 20px;overflow: hidden;" >
    <c:if test="${!used}">
        <button class="layui-btn select-goods">选择商品</button>
        <html:getGoodsByCode/>
    </c:if>

    <div style="float: right;">
        <button id="save" class="layui-btn">保存</button>
        <button class="layui-btn layui-btn-primary" id="cancel">取消</button>
    </div>
</div>

<div class="layuimini-container">
    <div class="layuimini-main">

        <h2 class="tableBeforeTitle">商品套餐</h2>
        <div style="height: 4px;background-color: #bbbbbb;width: 100%;margin: 20px 0 2px 0;"></div>
        <div style="height: 1px;width: 100%;background-color: #dddddd;margin-bottom: 10px;"></div>
        <div style="height: 10px;"></div>

        <form class="layui-form" lay-filter="form" action="">
            <input type="hidden" name="id" value="${id}">
            <button style="display: none;" lay-submit lay-filter="save" class="layui-btn">保存</button>
            <div class="layui-form-item">
                <div class="layui-inline" style="margin-bottom: 4px;">
                    <div class="label">编号</div>
                    <div style="display: inline-block;width: 160px;">
                        <input type="text" id="no" name="no" class="layui-input readonly" readonly style="font-size: 12px;">
                    </div>
                </div>

                <div class="layui-inline" style="margin-bottom: 4px;">
                    <div class="label">名称</div>
                    <div style="display: inline-block;width: 160px;">
                        <input type="text" id="name" name="name" class="layui-input" style="font-size: 12px;">
                    </div>
                </div>

                <div class="layui-inline" style="margin-bottom: 4px;">
                    <div class="label">状态</div>
                    <div style="display: inline-block; width: 160px;">
                        <input type="checkbox" checked="" name="status" lay-skin="switch" lay-filter="status" lay-text="正常|停用">
                    </div>
                </div>
            </div>

            <table class="layui-hide" id="table" lay-filter="table" lay-size="sm"></table>

            <table class="layui-table" style="margin: -1px 0 0 0;">
                <colgroup>
                    <col>
                    <col width="180">
                </colgroup>
                <tbody>
                    <tr>
                        <td>
                            <div style="position: relative">
                                <input type="text" id="remark" name="remark" class="layui-input" style="margin: 0px;padding-left: 60px; border-color:#e6e6e6">
                                <div style="position:absolute;top:0;left:10px;height: 38px;line-height: 38px;">备注</div>
                            </div>
                        </td>
                        <td>
                            <div style="position: relative">
                                <input type="number" id="totalAmount" name="totalAmount" class="layui-input" style="margin: 0px;padding-left: 60px; border-color:#e6e6e6">
                                <div style="position:absolute;top:0;left:10px;height: 38px;line-height: 38px;">套餐价</div>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>

        </form>
    </div>

    <script type="text/html" id="operBar">
        <a class="layui-btn layui-btn-xs layui-btn-danger table-operator" lay-event="delete">删除</a>
    </script>

    <script type="text/html" id="numberBar" >
        <div class="numberDiv">
            <input type="number" name="number" value="{{ getNumber(d.number) }}" class="layui-input number">
        </div>
    </script>

    <script type="text/html" id="amountBar" >
        <div class="numberDiv">
            <input type="number" name="amount" value="{{ getPrice(d.amount) }}" class="layui-input amount">
        </div>
    </script>

    <script type="text/html" id="priceBar" >
        <div class="priceDiv">
            <input type="number" name="price" value="{{ getPrice(d.price) }}" class="layui-input price">

            <div class="priceListDiv">
                <ul>
                    {{# if(d.unitId!=undefined){ }}
                    <li class="subjectPrice retailPrice" price="{{ getPrice(genUnitVo(d.goodsUnitVoList,d.unitId).retailPrice) }}">
                        零售价:{{ getPrice(genUnitVo(d.goodsUnitVoList,d.unitId).retailPrice) }}
                    </li>
                    <li class="subjectPrice wholesalePrice" price="{{ getPrice(genUnitVo(d.goodsUnitVoList,d.unitId).wholesalePrice) }}">
                        批发价:{{ getPrice(genUnitVo(d.goodsUnitVoList,d.unitId).wholesalePrice) }}
                    </li>
                    {{# } }}
                </ul>
            </div>
        </div>
    </script>
</div>
</body>
<html:loading/>
</html>